package com.rtx.wms.std.storer.service.impl;

import java.util.List;

import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rtx.api.annotation.DataSourceAnnotation;
import com.rtx.wms.std.common.bean.Storer;
import com.rtx.wms.std.common.bean.WmsConstant;
import com.rtx.wms.std.common.mapper.StorerMapper;
import com.rtx.wms.std.storer.service.StorerService;

import cn.hutool.core.util.StrUtil;

@Service
public class StorerServiceImpl extends ServiceImpl<StorerMapper, Storer> implements StorerService{
	

	@DataSourceAnnotation
	public Storer queryByStorerByDatasource(String datasourcekey,String storerkey) {
		LambdaQueryWrapper<Storer> qw = Wrappers.lambdaQuery();
		qw.eq(Storer::getStorerkey, storerkey);
		return baseMapper.selectOne(qw);
	}
	
	@DataSourceAnnotation
	public List<Storer> queryByStorerListByDatasource(String datasourcekey,Storer storer) {
		LambdaQueryWrapper<Storer> qw = Wrappers.lambdaQuery();
		qw.eq(Storer::getStorerkey, storer.getStorerkey());
		qw.eq(Storer::getType, storer.getType());
		return baseMapper.selectList(qw);
	}

	@DataSourceAnnotation
	public void addAndUpdataStorer(String datasource, Storer storer) {
		try {
			LambdaQueryWrapper<Storer> lqw = Wrappers.lambdaQuery();
			lqw.eq(Storer::getType, storer.getType());
			lqw.eq(Storer::getStorerkey, storer.getStorerkey());
			List<Storer> list = baseMapper.selectList(lqw);
			if(list !=null && list.size() > 0) {
				for(Storer s:list) {
					LambdaUpdateWrapper<Storer> upd = Wrappers.lambdaUpdate();
					upd.eq(Storer::getSerialkey, s.getSerialkey());
					upd.eq(Storer::getType, s.getType());
					upd.eq(Storer::getStorerkey, s.getStorerkey());
					storer.setSerialkey(null);
					baseMapper.rtxconfigUpdate(storer, upd);
				}
			}else {
				storer.setSerialkey(null);
				baseMapper.rtxconfigColumnsSave(storer);
			}
		} catch (Exception e) {
			log.error("新增或更新货主失败",e);
		}

	}

	@DataSourceAnnotation
	public List<Storer> queryDistributeStorer(String datasourcekey) {
		LambdaQueryWrapper<Storer> qw = Wrappers.lambdaQuery();
		qw.eq(Storer::getEdiflag, "P");
		qw.last("limit 500");
		return baseMapper.selectList(qw);
	};
	
	
	@DataSourceAnnotation
	public void updDistributeStorerStatus(String datasourcekey,String msg,Storer storer) {
		String status = "";
		if("ok".equals(msg)) {
			status =WmsConstant.SUCCESS_FLAG;
		}else {
			status =WmsConstant.FAIL_FLAG;
		}
		
		LambdaUpdateWrapper<Storer> upd = Wrappers.lambdaUpdate();
		upd.eq(Storer::getSerialkey, storer.getSerialkey());
		upd.set(Storer::getEdiflag, status);
		upd.set(Storer::getMsg, StrUtil.sub(msg,0,200));
		baseMapper.update(null, upd);
	};
}
